﻿using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor(typeof(Transform))]
public class TransformInspector : Editor
{
	public override void OnInspectorGUI()
	{
		Transform t = (Transform)target;

		Vector3 position = t.localPosition;
		Vector3 eulerAngles = t.localEulerAngles;
		Vector3 scale = t.localScale;
		
		EditorGUILayout.BeginHorizontal();
		{
			if (GUILayout.Button("P", GUILayout.Width(20)))
			{
				position = Vector3.zero;
			}
			
			if (GUILayout.Button("Snap", GUILayout.Width(45)))
			{
				position.x = RoundToNearest(position.x, 0.5f);
				position.y = RoundToNearest(position.y, 0.5f);
				position.z = RoundToNearest(position.z, 0.5f);
			}
			
			position = EditorGUILayout.Vector3Field("", position);
		}
		EditorGUILayout.EndHorizontal();
		
		EditorGUILayout.BeginHorizontal();
		{
			if (GUILayout.Button("R", GUILayout.Width(20)))
			{
				eulerAngles = Vector3.zero;
			}
			
			if (GUILayout.Button("Snap", GUILayout.Width(45)))
			{
				
				eulerAngles.x = RoundToNearest(eulerAngles.x, 45f);
				eulerAngles.y = RoundToNearest(eulerAngles.y, 45f);
				eulerAngles.z = RoundToNearest(eulerAngles.z, 45f);
			}
			
			eulerAngles = EditorGUILayout.Vector3Field("", eulerAngles);
		}
		EditorGUILayout.EndHorizontal();
		
		EditorGUILayout.BeginHorizontal();
		{
			if (GUILayout.Button("S", GUILayout.Width(20)))
			{
				scale = Vector3.one;
			}

			GUILayout.Space(49);
			
			scale = EditorGUILayout.Vector3Field("", scale);
		}
		EditorGUILayout.EndHorizontal();
		
		if (GUI.changed)
		{
			Undo.RegisterCompleteObjectUndo(t, "Transform Change");
			//Undo.RegisterUndo(t, "Transform Change");
			
			t.localPosition = FixIfNaN(position);
			t.localEulerAngles = FixIfNaN(eulerAngles);
			t.localScale = FixIfNaN(scale);
		}
	}

	private float RoundToNearest(float _n, float _nearest)
	{
		_n /= _nearest;
		_n = Mathf.Round(_n);
		_n *= _nearest;

		return _n;
	}
	
	private Vector3 FixIfNaN(Vector3 v)
	{
		if (float.IsNaN(v.x))
		{
			v.x = 0;
		}
		if (float.IsNaN(v.y))
		{
			v.y = 0;
		}
		if (float.IsNaN(v.z))
		{
			v.z = 0;
		}
		return v;
	}
	
}